<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px"
			class="queryForms">
			<el-form-item label="工序名称" prop="processName">
				<el-input maxlength="20" show-word-limit v-model="queryParams.processName" placeholder="请输入工序名称"
					clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="工艺流状态" prop="processState">
				<el-select v-model="queryParams.processState" placeholder="工艺流状态" clearable>
					<el-option v-for="dict in dict.type.default_status" :key="dict.value" :label="dict.label"
						:value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['erp:productProcess:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
					v-hasPermi="['erp:productProcess:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini" type="info" @click="handleBacks">返回</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini" type="info" @click="handleViews"
					v-hasPermi="['erp:productProcess:viewContent']">预览填报内容</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini">{{ $route.query.productName }}-{{ $route.query.productModel }}</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="productProcess31" :showSearch.sync="showSearch"
				@queryTable="getList" :columns.sync="columns"></right-toolbar>
		</el-row>

		<div class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="productProcessList"
				@selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55" />
				<!-- <el-table-column label="工序编码" prop="processCode" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" /> -->
				<el-table-column label="工序名称" prop="processName" min-width="280" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="工时" align="center" prop="processTime" min-width="70"
					:show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="工序状态" align="center" prop="processState" min-width="70"
					:show-overflow-tooltip="true" v-if="columns[2].visible">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.processState" active-value="1" inactive-value="0"
							@change="handleStatusChange(scope.row)"> </el-switch>
					</template>
				</el-table-column>
				<el-table-column label="工卡顺序" align="center" prop="postSort" min-width="80"
					:show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="创建人" align="center" prop="createBy" min-width="70" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="创建时间" align="center" prop="createTime" min-width="110"
					:show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
					width="230">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleContent(scope.row)"
							v-hasPermi="['erp:productProcess:content']">填报内容</el-button>
						<el-button size="mini" type="text" icon="el-icon-document" @click="handleSteps(scope.row)"
							v-hasPermi="['erp:productProcess:steps']">外委工序</el-button>
						<el-dropdown size="mini" @command="command => handleCommand(command, scope.row)"
							v-hasPermi="['erp:productProcess:edit', 'erp:productProcess:remove']">
							<el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="handleUpdate"
									v-hasPermi="['erp:productProcess:edit']">修改</el-dropdown-item>
								<el-dropdown-item command="handleDelete"
									v-hasPermi="['erp:productProcess:remove']">删除</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination menuNames="Pagination1002" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />
		<!-- <el-pagination class="pageSize" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> -->
		<!-- 添加或修改产品工序对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag @close="close">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-row :gutter="20">
					<!-- <el-col :span="12">
						<el-form-item label="工序编码" prop="processCode">
							<el-input v-model="form.processCode" placeholder="请输入工序编码" maxlength="20" show-word-limit  />
						</el-form-item>
					</el-col> -->
					<el-col :span="12">
						<el-form-item label="工序名称" prop="processName">
							<el-input v-model="form.processName" placeholder="请输入工序名称" maxlength="50" show-word-limit />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工时" prop="processTime">
							<el-input-number v-model="form.processTime" :precision="2" :step="0.1" :min="1"
								:max="100000000000"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="technologyDictCode == '6'">
						<el-form-item label="工序类型" prop="processType">
							<el-select v-model="form.processType" clearable>
								<el-option v-for="item in processTypeList" :key="item.id" :value="item.id"
									:label="item.name"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="technologyDictCode == '7'">
						<el-form-item label="工序类型" prop="processType">
							<el-select v-model="form.processType" clearable>
								<el-option v-for="item in processTypeList1" :key="item.id" :value="item.id"
									:label="item.name"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工序状态" prop="processState">
							<el-radio-group v-model="form.processState">
								<el-radio v-for="dict in dict.type.default_status" :key="dict.value"
									:label="dict.value">{{
										dict.label }}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="印章数" prop="stampsNumber">
							<el-select v-model="form.stampsNumber">
								<el-option v-for="item in numberList" :key="item.id" :value="item.id"
									:label="item.name"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="form.stampsNumber == '2'">
						<el-form-item label="印章空格数" prop="stampsBlankNumber">
							<el-input-number v-model="form.stampsBlankNumber" :step="1" :min="1"
								:max="100000000000"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="form.stampsNumber == '2'">
						<el-form-item label="印章前空格数" prop="stampsFrontBlankNumber">
							<el-input-number v-model="form.stampsFrontBlankNumber" :step="1" :min="1"
								:max="100000000000"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工卡顺序" prop="postSort">
							<el-input-number v-model="form.postSort" :step="1" :min="1"
								:max="100000000000"></el-input-number>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 添加内容 -->
		<!-- width="800px" -->
		<el-dialog title="添加填报内容" :visible.sync="openContent" width="1850px" append-to-body v-dialogDrag
			@close="closewhite">
			<div style="display: flex; justify-content: space-around; height: 715px; overflow-y: auto">
				<div v-if="previewUrl" style="width: 900px">
					<vue-office-pdf :src="previewUrl" style="width: 900px; overflow-x: auto; height: 70vh"
						:key="componentKey"></vue-office-pdf>
				</div>
				<div style="width: 800px; margin-top: 35px">
					<ckeditor @input="change2" @ready="onEditorReady" ref="refCKEditor" :config="config"
						v-model="editorData" :read-only="only" :throttle="120" :editor-url="editorUrl"></ckeditor>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="viewContent(1)">预 览</el-button>
				<el-button type="primary" @click="submitContent(2)">确 定</el-button>
				<el-button @click="closeContent">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="预览" :visible.sync="openPreview" width="1000px" append-to-body v-dialogDrag>
			<vue-office-pdf :src="previewUrl" style="width: 900px; overflow-x: auto; height: 80vh"></vue-office-pdf>
		</el-dialog>
	</div>
</template>
<script>
import CKEditor from "ckeditor4-vue"
import VueOfficePdf from "@vue-office/pdf"
import previewExcel from "@/views/components/previewTemplete/pdfPreview.vue"
window.JSZip = require("jszip")
import { productPart1, getcolumn } from "@/api/selectList"
import { mapGetters } from "vuex"
import { getproductTechnology, exportWorkCard1, listProductProcess, getProductProcess, delProductProcess, addProductProcess, updateProductProcess } from "@/api/productTechnology/productProcess"
export default {
	dicts: ["default_status"],
	name: "productProcess",
	computed: {
		...mapGetters(["sidebar"])
	},
	components: {
		ckeditor: CKEditor.component,
		previewExcel,
		VueOfficePdf
	},
	data() {
		return {
			ispaste: true,
			currentVersionIds: [],
			componentKey: 0,
			numberList: [
				{
					id: 1,
					name: "1"
				},
				{
					id: 2,
					name: "2"
				}
			],
			openPreview: false,
			previewType: "",
			currentVersionId: "",
			technologyDictCode: "",
			eleTabTop: 0, //表格容器距浏览器顶部距离
			processTypeList1: [
				{
					id: "5",
					name: "电镀"
				},
				{
					id: "6",
					name: "喷漆"
				}
			],
			processTypeList: [
				{
					id: "1",
					name: "弹簧测力"
				},
				{
					id: "2",
					name: "涡流探伤"
				},
				{
					id: "3",
					name: "磁粉探伤"
				},
				{
					id: "4",
					name: "渗透无损探伤"
				}
			],
			editor: null,
			only: false,
			config: {
				textfield: [],
				height: "550px",
				allowedContent: true, // 允许任何内容
				extraPlugins: "widget",
				// extraPlugins: "myInputWidget",
				// extraPlugins: "myinputwidget",
				// allowedContent: "myinputwidget", // 允许我们的自定义widget
				// 配置 Widget 插件
				widgets: {
					inputWidget: {
						// 选择器，选择td内的input元素
						selector: 'td > input[type="text"]',
						// 定义 widget 的初始化逻辑
						upcast: element => {
							return element.name === "input" && element.getAttribute("type") === "text"
						},
						// 定义 widget 的模板，这里只是示例，具体根据需求来定义
						template: element => {
							return new CKEDITOR.dom.element("input", element.document)
						}
						// 其他配置...
					}
				},
				// 工具栏
				toolbarGroups: [
					{ name: "document", groups: ["mode", "document", "doctools"] },
					{ name: "clipboard", groups: ["clipboard", "undo"] },
					{
						name: "editing",
						groups: ["find", "selection", "spellchecker", "editing"]
					},
					{ name: "forms", groups: ["forms"] },
					{ name: "basicstyles", groups: ["basicstyles", "cleanup"] },
					{
						name: "paragraph",
						groups: ["list", "indent", "blocks", "align", "bidi", "paragraph"]
					},
					{ name: "links", groups: ["links"] },
					{ name: "insert", groups: ["insert"] },
					{ name: "styles", groups: ["styles"] },
					//   { name: "colors", groups: ["colors"] },
					// { name: "tools", groups: ["tools"] },
					{ name: "others", groups: ["others"] }
					// { name: "about", groups: ["about"] }
				],
				//   extraPlugins: "notification",
				//   // toolbar 中的一些配置功能 需要在这里添加一下才可以用 例如 print colorbutton
				extraPlugins: "print,format,font,colorbutton,justify,notification",
				// 删除的工具栏
				// Checkbox,Radio,TextField,Outdent,Indent,,
				removeButtons: "Styles,Format,FormatOutdent,Indent,NumberedList,Copy,Paste,BulletedList,Source,Form,SelectAll,Select,CopyFormatting,Scayt,HiddenField,Subscript,Superscript,SpecialChar,About,Image,Screen,Source,uploadimage,Form,Save,NewPage,ExportPdf,Preview,Print,Templates,Cut,PasteText,PasteFromWord,Undo,Redo,Replace,Find,Textarea,Button,ImageButton,Language,Unlink,Link,Anchor,HorizontalRule,Smiley,,BidiRtl,PageBreak,Iframe,ShowBlocks,CreateDiv,Blockquote,BidiLtr"
			},
			editorId: "",
			editorData: "",
			editorUrl: "/ckeditor/ckeditor.js", //将指令的值更改为指向所需的 CKEditor 4 脚本位置来更改
			openContent: false,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 产品工序表格数据
			productProcessList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				productId: null,
				productTechnologyId: null,
				processCode: null,
				processName: null,
				processTime: null,
				processState: null,
				content: null
			},
			// 表单参数
			form: { processState: "1", productId: localStorage.getItem("productId1") },
			// 表单校验
			rules: {
				// processCode: [{ required: true, message: "工序编码不能为空", trigger: "blur" }],
				processName: [{ required: true, message: "工序名称不能为空", trigger: "blur" }],
				processTime: [{ required: true, message: "工时不能为空", trigger: "blur" }]
			},
			// 列信息
			columns: [
				{ key: 0, label: `工序名称`, visible: true },
				{ key: 1, label: `工时`, visible: true },
				{ key: 2, label: `工序状态`, visible: true },
				{ key: 3, label: `创建人`, visible: true },
				{ key: 4, label: `创建时间`, visible: true },
				{ key: 5, label: `工卡顺序`, visible: true }
			],
			previewUrl: "",
			productTechnologyId: "",
			technologyDictCode: "",
			productId: ""
		}
	},

	created() {

	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
		this.$refs.table.doLayout()
		this.$nextTick(() => {
			this.$refs.table.doLayout()
		})
	},
	activated() {
		this.productId = this.$route.query.productId
		this.productTechnologyId = this.$route.query.id
		this.technologyDictCode = this.$route.query.technologyDictCode
		this.getSize()
		this.$forceUpdate()
		this.getproductPart1()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
		this.$nextTick(() => {
			this.$refs.table.doLayout()
		})
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	inject: ["reload"],
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination1002" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		change2(e) {
			var parser = new DOMParser()
			var pastedDoc = parser.parseFromString(this.editorData, "text/html")
			const ps = pastedDoc.querySelectorAll("p")
			const tds = pastedDoc.querySelectorAll("td")
			var additionalCharacter = "\u200B"
			if (tds.length) {
				for (let i = 0; i < tds.length; i++) {
					// 设置文本颜色
					var inputs = tds[i].getElementsByTagName("input")
					if (!tds[i].textContent) {
						var tdElement = tds[i]
						var siblingElements = tdElement.nextElementSibling
						// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
						if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
							// 创建一个文本节点并添加字符
							var textNode = document.createTextNode(additionalCharacter)

							// 将文本节点插入到input元素之后
							tdElement.parentNode.insertBefore(textNode, tdElement.nextSibling)
							// inputElement.parentNode.insertBefore(textNode, inputElement)
						}
						for (let j = 0; j < inputs.length; j++) {
							var inputElement = inputs[j]
							var siblingElements = inputElement.nextElementSibling
							// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
							if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
								// 创建一个文本节点并添加字符
								var textNode = document.createTextNode(additionalCharacter)
								// 将文本节点插入到input元素之后
								inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
								// inputElement.parentNode.insertBefore(textNode, inputElement)
							}
						}
					}
				}
			}
			if (ps.length) {
				for (let i = 0; i < ps.length; i++) {
					ps[i].style.setProperty("font-family", "宋体")
					ps[i].style.setProperty("font-size", "12px")
					// 设置文本颜色
					var inputs = ps[i].getElementsByTagName("input")
					if (ps[i].parentNode.tagName == "TD") {
						if (!ps[i].textContent) {
							for (let j = 0; j < inputs.length; j++) {
								var inputElement = inputs[j]
								var siblingElements = inputElement.nextElementSibling
								// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
								if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
									// 创建一个文本节点并添加字符
									var textNode = document.createTextNode(additionalCharacter)
									// 将文本节点插入到input元素之后
									inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
									// inputElement.parentNode.insertBefore(textNode, inputElement)
								}
							}
						}
					}
				}
			}
			const editor = this.$refs.refCKEditor.editor
			const selection = editor.getSelection()
			const range = selection.getRanges()[0] // 保存当前的选区范围
			var serializer = new XMLSerializer()
			// 将文档对象转换为HTML字符串
			var htmlString = serializer.serializeToString(pastedDoc)
			var doc1 = parser.parseFromString(htmlString, "text/html")
			var ols1 = doc1.querySelectorAll("body")
			// 获取body元素内的HTML内容
			var bodyContent = ols1[0].innerHTML
			this.editorData = bodyContent

			this.$nextTick(() => {
				if (range) {
					range.select()
					this.ispaste = false
				}
			})
		},
		handleViews() {
			getproductTechnology(this.productTechnologyId).then(res => {
				const loading = this.$loading({
					lock: true,
					text: "Loading",
					spinner: "el-icon-loading",
					background: "rgba(0, 0, 0, 0.7)"
				})
				const formData = new FormData()
				formData.append("id", res.data.currentVersionId)
				exportWorkCard1(formData)
					.then(res => {
						this.componentKey += 1 // 改变key值，重新渲染子组件
						this.previewUrl = res.msg
						this.previewType == "pdf"
						this.openPreview = true
						loading.close()
					})
					.catch(err => {
						loading.close()
					})
			})
		},
		handleSizeChange(val) {
			this.queryParams.pageSize = val
			localStorage.setItem("pageSize", this.queryParams.pageSize)
			// this.queryParams.pageNum = 1
			this.getList()
		},
		handleCurrentChange(val) {
			// 当前页
			this.queryParams.pageNum = val
			localStorage.setItem("pageNum", this.queryParams.pageNum)
			this.getList()
			// this.currentPage = val
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		handleBacks() {
			const obj = { path: this.$route.path }
			this.$tab.closePage(obj).then(() => {
				this.$router.go(-1)
				// this.$router.push({
				// 	path: `/productTechnology/Technology/productTechnologyName/index`,
				// 	query: {
				// 		productName: this.$route.query.productName,
				// 		productModel: this.$route.query.productModel
				// 	}
				// })
			})
		},
		close() {
			this.open = false
			this.reset()
			this.reload()
			this.getList()
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		closeContent() {
			this.openContent = false
			this.reload()
			this.getList()
		},
		getproductPart1() {
			this.config.textfield = []
			productPart1(this.productId).then(res => {
				res.rows.forEach((item, index) => {
					item.name = "(" + (index + 1) + ") " + item.partName + "(" + item.partFigure + ")"
					this.config.textfield.push([item.name, item.partId])
				})
			})
		},
		closewhite() {
			this.openContent = false
			// 刷新浏览器
			this.reload()
			this.getList()
		},
		hasNestedTags(pElement) {
			// 遍历<p>元素的所有子节点
			for (var i = 0; i < pElement.childNodes.length; i++) {
				var child = pElement.childNodes[i]
				// 如果发现任何子节点是元素节点（即嵌套的标签），返回true
				if (child.nodeType === Node.ELEMENT_NODE) {
					return true
				}
			}
			// 如果没有发现嵌套的标签，返回false
			return false
		},

		containsOnlySpaces(pElement) {
			// 检查<p>元素是否有子元素，排除文本节点和注释节点
			for (var child = pElement.firstChild; child; child = child.nextSibling) {
				if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.COMMENT_NODE) {
					// 如果发现任何子节点不是文本节点也不是注释节点，说明有嵌套标签
					return false
				}
			}
			// 获取<p>标签的文本内容，并检查是否只包含空格
			var textContent = pElement.textContent || pElement.innerText
			return /^\s*$/.test(textContent)
		},
		submitData(status) {
			if (this.editorData) {
				var parser = new DOMParser()
				var doc = parser.parseFromString(this.editorData, "text/html")
				var ols = doc.querySelectorAll("li")
				var olElements = doc.querySelectorAll("ol")
				var pElements = doc.querySelectorAll("p")
				var tds = doc.querySelectorAll("td")
				var inputElements = doc.querySelectorAll("input")
				var additionalCharacter = "\u200B"
				if (inputElements.length) {
					for (let i = 0; i < inputElements.length; i++) {
						if (inputElements[i].getAttribute("type") == "text") {
							// inputElements[i].style.setProperty("text-align", "center")
							inputElements[i].style.setProperty("font-family", "Times New Roman")
							inputElements[i].style.setProperty("font-size", "12px")
							// inputElements[i].style.setProperty("pointer-events", "auto")
							console.log(inputElements[i])
							if (inputElements[i].getAttribute("value")) {
								inputElements[i].setAttribute("disable", "true")
							} else {
								inputElements[i].setAttribute("disable", "false")
							}
						}
					}
				}
				// 遍历所有的ol元素
				for (var i = olElements.length - 1; i >= 0; i--) {
					// 保存当前ol元素的父节点，以便之后可以引用它
					var parent = olElements[i].parentNode
					// 创建一个临时的div元素，用于存放li元素
					var tempDiv = document.createElement("div")
					// 遍历当前ol元素的所有子节点
					while (olElements[i].firstChild) {
						// 将li元素移动到临时div中
						tempDiv.appendChild(olElements[i].firstChild)
					}
					// 将临时div中的所有子节点（即原来的li元素）直接添加到ol元素的父节点中
					while (tempDiv.firstChild) {
						parent.insertBefore(tempDiv.firstChild, olElements[i])
					}
					// 删除原始的ol元素
					parent.removeChild(olElements[i])
				}
				if (ols.length) {
					for (var i = 0; i < ols.length; i++) {
						var ol = ols[i] // 当前遍历到的 ol 元素
						// 创建新的 p 元素并复制原始 ol 中的文本内容
						var newP = document.createElement("p")
						newP.textContent = ol.innerText || ol.textContent
						// 复制原始 ol 中的属性到新的 p 元素上
						for (var j = 0; j < ol.attributes.length; j++) {
							var attrName = ol.attributes[j].name
							if (!newP.hasAttribute(attrName)) {
								newP.setAttribute(attrName, ol.getAttribute(attrName))
							}
						}
						// 移除原始 ol 元素
						ol.parentNode.replaceChild(newP, ol)
					}
				}

				if (pElements.length) {
					for (let i = 0; i < pElements.length; i++) {
						// 设置文本颜色
						if (pElements[i].parentNode.tagName !== "TD") {
							// 如果不是，设置样式
							pElements[i].style.setProperty("letter-spacing", "0.1px")
							pElements[i].style.setProperty("margin-top", "5px")
							pElements[i].style.setProperty("margin-bottom", "5px")
							pElements[i].style.setProperty("margin-left", "0px")
							pElements[i].style.setProperty("margin-right", "0px")
							// 设置背景颜色
							pElements[i].style.setProperty("padding-top", "5px")
							pElements[i].style.setProperty("padding-bottom", "5px")
							pElements[i].style.setProperty("padding-left", "0px")
							pElements[i].style.setProperty("padding-right", "0px")
							// pElements[i].style.setProperty("line-height", "10")
						} else {
							pElements[i].style.setProperty("margin-top", "0px")
							pElements[i].style.setProperty("margin-bottom", "0px")
							pElements[i].style.setProperty("margin-left", "0px")
							pElements[i].style.setProperty("margin-right", "0px")
							// 设置背景颜色
							pElements[i].style.setProperty("padding-top", "0px")
							pElements[i].style.setProperty("padding-bottom", "0px")
							pElements[i].style.setProperty("padding-left", "0px")
							pElements[i].style.setProperty("padding-right", "0px")
							// pElements[i].style.setProperty("text-align", "center")

							var inputs = pElements[i].getElementsByTagName("input")
							if (!pElements[i].textContent) {
								for (let j = 0; j < inputs.length; j++) {
									var inputElement = inputs[j]
									var siblingElements = inputElement.nextElementSibling
									// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
									if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
										// 创建一个文本节点并添加字符
										var textNode = document.createTextNode(additionalCharacter)
										// 将文本节点插入到input元素之后
										inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
										// inputElement.parentNode.insertBefore(textNode, inputElement)
									}
								}
							}
						}
					}
				}

				if (tds.length) {
					for (let i = 0; i < tds.length; i++) {
						// 设置文本颜色
						var inputs = tds[i].getElementsByTagName("input")
						if (!tds[i].textContent) {
							for (let j = 0; j < inputs.length; j++) {
								var inputElement = inputs[j]
								var siblingElements = inputElement.nextElementSibling
								// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
								if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
									// 创建一个文本节点并添加字符
									var textNode = document.createTextNode(additionalCharacter)

									// 将文本节点插入到input元素之后
									inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
									// inputElement.parentNode.insertBefore(textNode, inputElement)
								}
							}
						}
					}
				}
				// 获取文档对象（上述代码生成）
				// 创建XMLSerializer对象
				var serializer = new XMLSerializer()
				// 将文档对象转换为HTML字符串
				var htmlString = serializer.serializeToString(doc)
				// console.log(htmlString)
				var doc1 = parser.parseFromString(htmlString, "text/html")
				var ols1 = doc1.querySelectorAll("body")

				// 获取body元素内的HTML内容
				var bodyContent = ols1[0].innerHTML
				console.log(bodyContent)
				// 现在，bodyContent变量包含了<body>标签内的所有内容
				updateProductProcess({
					id: this.editorId,
					content: bodyContent
				}).then(res => {
					if (status == 2) {
						this.$modal.msgSuccess("设置成功")
						this.openContent = false
						this.getList()
						// 刷新浏览器
						this.reload()
					} else {
						const loading = this.$loading({
							lock: true,
							text: "Loading",
							spinner: "el-icon-loading",
							background: "rgba(0, 0, 0, 0.7)"
						})
						const formData = new FormData()
						formData.append("id", this.currentVersionId)
						exportWorkCard1(formData)
							.then(res => {
								this.$modal.msgSuccess("设置成功")
								this.componentKey += 1 // 改变key值，重新渲染子组件
								this.previewUrl = res.msg
								this.previewType == "pdf"
								loading.close()
							})
							.catch(err => {
								loading.close()
							})
					}
				})
			} else {
				this.$modal.msgError("请先进行内容填报")
			}
		},
		previewFile(blob) {
			console.log(blob.type, "blob.type")
			// 创建一个临时的URL
			const url = window.URL.createObjectURL(blob)
			console.log(url, "blob.typeurlurlurl")
			// 根据文件类型，使用不同的HTML元素进行预览
			if (blob.type.startsWith("image/")) {
				// 图片文件直接在<img>标签中预览
				const img = document.createElement("img")
				img.src = url
				img.style.width = "100%"
				document.body.appendChild(img)
			} else if (blob.type.startsWith("text/")) {
				// 文本文件可以使用<iframe>或<pre>标签展示内容
				const iframe = document.createElement("iframe")
				iframe.src = url
				iframe.style.width = "100%"
				iframe.style.height = "600px"
				document.body.appendChild(iframe)
			} else {
				// 其他文件类型可以直接放一个链接供用户点击打开或下载
				const link = document.createElement("a")
				link.href = url
				link.textContent = "Open/Download"
				document.body.appendChild(link)
			}
		},
		viewContent(status) {
			this.submitData(status)
		},
		submitContent(status) {
			this.submitData(status)
		},
		// 更多操作触发
		handleCommand(command, row) {
			switch (command) {
				case "handleUpdate":
					this.handleUpdate(row)
					break
				case "handleDelete":
					this.handleDelete(row)
					break
				default:
					break
			}
		},
		handleContent(row) {
			this.currentVersionId = row.currentVersionId
			this.editorId = row.id
			this.getDetail(row.id, 2)
		},
		handleSteps(row) {
			localStorage.setItem("productProcessId", row.id)
			localStorage.setItem("productId2", row.productId)
			this.$router.push({
				path: "/productTechnology/Technology/productProcessStep/index",
				query: {
					id: row.id,
					productId: row.productId,
					productName: this.$route.query.productName,
					productModel: this.$route.query.productModel
				}
			})
		},
		// 状态修改
		handleStatusChange(row) {
			this.$modal
				.confirm("确认要修改工序流状态吗？")
				.then(function () {
					return updateProductProcess({
						id: row.id,
						processState: row.processState
					})
				})
				.then(() => {
					this.$modal.msgSuccess("修改成功")
				})
				.catch(function () {
					row.processState = row.processState === "0" ? "1" : "0"
				})
		},
		/** 查询产品工序列表 */
		getList() {
			this.loading = true
			this.queryParams.productTechnologyId = this.productTechnologyId
			listProductProcess(this.queryParams).then(response => {
				this.productProcessList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
			this.reload()
			this.getList()
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				productTechnologyId: null,
				processCode: null,
				processName: null,
				processTime: null,
				processState: "1",
				productId: this.productId,
				content: null,
				postSort: this.total + 1
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.currentVersionIds = selection.map(item => item.currentVersionId)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset()
			this.form.productTechnologyId = this.productTechnologyId
			this.open = true
			this.title = "添加产品工序"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			this.title = "修改产品工序"
			this.getDetail(row.id, 1)
		},
		onEditorReady(editor) {
			const _this = this
			_this.editor = _this.$refs.refCKEditor.instance
			if (_this.form.content) {
				_this.editor.setData(_this.form.content)
			}
			// 定义自定义的 CKEditor Widget
			CKEDITOR.plugins.add("myInputWidget", {
				requires: "widget",
				init: function (editor) {
					editor.widgets.add("MyInputWidget", {
						template: '<input type="text" placeholder="Type here..." />',
						// 选择器，选择td内的input元素
						selector: 'td > input[type="text"]',
						// 定义 widget 的初始化逻辑
						upcast: element => {
							return element.name === "input" && element.getAttribute("type") === "text"
						}
					})
				}
			})
			// 定义自定义的 CKEditor Widget
			// CKEDITOR.plugins.add("myinputwidget", {
			// 	requires: "widget",
			// 	init: function (editor) {
			// 		editor.widgets.add("MyInputWidget", {
			// 			template: '<input type="text" placeholder="Enter text" class="my-input-widget"/>',
			// 			downcast: function (element) {
			// 				return element.name == "input" ? new CKEDITOR.htmlParser.text(element.getAttribute("data-cke-input-value")) : false
			// 			},
			// 			upcast: function (element, data) {
			// 				var ret = element.name == "input" && element.hasClass("my-input-widget")
			// 				if (ret) {
			// 					data["data-cke-input-value"] = element.getValue()
			// 				}
			// 				return ret
			// 			}
			// 		})
			// 	}
			// })
			_this.editor.on("paste", function (evt) {
				// this.ispaste = true
				// 将粘贴的表格宽度设置为固定值
				const parser = new DOMParser()
				const pastedDoc = parser.parseFromString(evt.data.dataValue, "text/html")
				const tables = pastedDoc.querySelectorAll("table")
				const ps = pastedDoc.querySelectorAll("p")
				const tds = pastedDoc.querySelectorAll("td")
				var additionalCharacter = "\u200B"
				const spans = pastedDoc.querySelectorAll("span")
				const inputs1 = pastedDoc.querySelectorAll("input")
				const fonts = pastedDoc.querySelectorAll("font")
				if (inputs1.length) {
					for (let i = 0; i < inputs1.length; i++) {
						var inputElement = inputs1[i]
						var siblingElements = inputElement.nextElementSibling
						// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
						if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
							// 创建一个文本节点并添加字符
							var textNode = document.createTextNode(additionalCharacter)
							// 将文本节点插入到input元素之后
							inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
							// inputElement.parentNode.insertBefore(textNode, inputElement)
						}
					}
				}

				if (tds.length) {
					for (let i = 0; i < tds.length; i++) {
						// 设置文本颜色
						var inputs = tds[i].getElementsByTagName("input")
						if (!tds[i].textContent) {
							var tdElement = tds[i]
							var siblingElements = tdElement.nextElementSibling
							// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
							if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
								// 创建一个文本节点并添加字符
								var textNode = document.createTextNode(additionalCharacter)

								// 将文本节点插入到input元素之后
								tdElement.parentNode.insertBefore(textNode, tdElement.nextSibling)
								// inputElement.parentNode.insertBefore(textNode, inputElement)
							}
							for (let j = 0; j < inputs.length; j++) {
								var inputElement = inputs[j]
								var siblingElements = inputElement.nextElementSibling
								// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
								if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
									// 创建一个文本节点并添加字符
									var textNode = document.createTextNode(additionalCharacter)

									// 将文本节点插入到input元素之后
									inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
									// inputElement.parentNode.insertBefore(textNode, inputElement)
								}
							}
						}
					}
				}
				tables.forEach(item => {
					item.style.setProperty("width", "500px")
					item.style.setProperty("font-size", "12px")
					// item.style.setProperty("text-align", "center")
				})
				if (ps.length) {
					for (let i = 0; i < ps.length; i++) {
						ps[i].style.setProperty("font-family", "宋体")
						ps[i].style.setProperty("font-size", "12px")
						// 设置文本颜色
						if (ps[i].parentNode.tagName == "TD") {
							if (!ps[i].textContent) {
								// ps[i].textContent = ps[i].textContent + "?"
								var inputs = tds[i].getElementsByTagName("input")
								for (let j = 0; j < inputs.length; j++) {
									var inputElement = inputs[j]
									var siblingElements = inputElement.nextElementSibling
									// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
									if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
										// 创建一个文本节点并添加字符
										var textNode = document.createTextNode(additionalCharacter)
										// 将文本节点插入到input元素之后
										inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
										// inputElement.parentNode.insertBefore(textNode, inputElement)
									}
								}
							}
						}
					}
				}
				if (fonts.length) {
					for (var i = 0; i < fonts.length; i++) {
						var ol = fonts[i] // 当前遍历到的 font 元素
						// 创建新的 span元素并复制原始 font 中的文本内容
						var newP = document.createElement("span")
						newP.textContent = ol.innerText || ol.textContent
						newP.removeAttribute("face")
						newP.style.setProperty("font-family", "宋体")
						newP.style.setProperty("font-size", "12px")
						// newP.style.setProperty("line-height", "10")
						// 移除原始 font 元素
						ol.parentNode.replaceChild(newP, ol)
					}
				}
				spans.forEach(item => {
					item.style.setProperty("font-family", "宋体")
					item.style.setProperty("font-size", "12px")
					// item.style.setProperty("line-height", "10")
				})
				var serializer = new XMLSerializer()
				// 将文档对象转换为HTML字符串
				var htmlString = serializer.serializeToString(pastedDoc)
				var doc1 = parser.parseFromString(htmlString, "text/html")
				var ols1 = doc1.querySelectorAll("body")
				// 获取body元素内的HTML内容
				var bodyContent = ols1[0].innerHTML
				evt.data.dataValue = bodyContent

				if (pastedDoc.body.firstChild && pastedDoc.body.firstChild.tagName === "INPUT") {
					console.log("粘贴的内容只包含一个 <input> 标签")
					this.ispaste = true
					// 如果只包含 input 标签，你可以在这里添加额外的逻辑
				} else {
					this.ispaste = false
					console.log("粘贴的内容包含其他元素或文本")
					// 如果不是只包含 input 标签，可以在这里处理其他情况
				}
			})
		},
		getDetail(id, status) {
			getProductProcess(id).then(response => {
				this.form = response.data
				var parser = new DOMParser()

				var pastedDoc = parser.parseFromString(this.form.content, "text/html")
				const ps = pastedDoc.querySelectorAll("p")
				const tds = pastedDoc.querySelectorAll("td")
				var additionalCharacter = "\u200B"
				if (tds.length) {
					for (let i = 0; i < tds.length; i++) {
						// 设置文本颜色
						var inputs = tds[i].getElementsByTagName("input")
						if (!tds[i].textContent) {
							var tdElement = tds[i]
							var siblingElements = tdElement.nextElementSibling
							// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
							if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
								// 创建一个文本节点并添加字符
								var textNode = document.createTextNode(additionalCharacter)

								// 将文本节点插入到input元素之后
								tdElement.parentNode.insertBefore(textNode, tdElement.nextSibling)
								// inputElement.parentNode.insertBefore(textNode, inputElement)
							}
							for (let j = 0; j < inputs.length; j++) {
								var inputElement = inputs[j]
								var siblingElements = inputElement.nextElementSibling
								// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
								if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
									// 创建一个文本节点并添加字符
									var textNode = document.createTextNode(additionalCharacter)
									// 将文本节点插入到input元素之后
									inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
									// inputElement.parentNode.insertBefore(textNode, inputElement)
								}
							}
						}
					}
				}
				if (ps.length) {
					for (let i = 0; i < ps.length; i++) {
						ps[i].style.setProperty("font-family", "宋体")
						ps[i].style.setProperty("font-size", "12px")
						// 设置文本颜色
						var inputs = ps[i].getElementsByTagName("input")
						if (ps[i].parentNode.tagName == "TD") {
							if (!ps[i].textContent) {
								// ps[i].textContent = ps[i].textContent + "?"

								for (let j = 0; j < inputs.length; j++) {
									var inputElement = inputs[j]
									var siblingElements = inputElement.nextElementSibling
									// 如果没有兄弟元素，或者第一个兄弟元素不是文本节点，就在input元素后面添加字符
									if (!siblingElements || siblingElements.nodeType !== Node.TEXT_NODE) {
										// 创建一个文本节点并添加字符
										var textNode = document.createTextNode(additionalCharacter)
										// 将文本节点插入到input元素之后
										inputElement.parentNode.insertBefore(textNode, inputElement.nextSibling)
										// inputElement.parentNode.insertBefore(textNode, inputElement)
									}
								}
							}
						}
					}
				}
				var serializer = new XMLSerializer()
				// 将文档对象转换为HTML字符串
				var htmlString = serializer.serializeToString(pastedDoc)
				var doc1 = parser.parseFromString(htmlString, "text/html")
				var ols1 = doc1.querySelectorAll("body")
				// 获取body元素内的HTML内容
				var bodyContent = ols1[0].innerHTML
				this.form.content = bodyContent
				if (status == 1) {
					this.open = true
				} else {
					if (this.editor) {
						this.editor.setData(this.form.content)
					}
					const loading = this.$loading({
						lock: true,
						text: "Loading",
						spinner: "el-icon-loading",
						background: "rgba(0, 0, 0, 0.7)"
					})
					const formData = new FormData()
					formData.append("id", this.currentVersionId)
					exportWorkCard1(formData)
						.then(res => {
							this.openContent = true
							this.previewUrl = res.msg
							this.previewType == "pdf"
							// this.ispaste = false
							loading.close()
						})
						.catch(err => {
							loading.close()
						})
				}
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.id != null) {
						updateProductProcess(this.form).then(response => {
							this.$modal.msgSuccess("修改成功")
							this.open = false
							this.reload()
							this.getList()
						})
					} else {
						addProductProcess(this.form).then(response => {
							this.$modal.msgSuccess("新增成功")
							this.open = false
							this.reload()
							this.getList()
						})
					}
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除产品工序数据项？")
				.then(function () {
					return delProductProcess(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"erp/productProcess/export",
				{
					...this.queryParams
				},
				`productProcess_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style scss scoped>
::v-deep .el-dialog:not(.is-fullscreen) {
	margin-top: 4vh !important;
}

.pageSize {
	text-align: right;
	margin-right: 20px;
}

::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 230px !important;
}
</style>
